<template>
  <div>
    <van-field autocomplete="off"
      v-model="calendarValue"
      center
      clearable
      readonly
      clickable
      :label="label + '时间'"
      placeholder="请选择"
      @click="showTimePicker = true"
    >
      <template #button>
        <!-- 避免事件冒泡   -->
        <van-button type="info" size="mini" native-type="button" @click.stop="doSearchByDate">查询</van-button>
      </template>
    </van-field>

    <van-popup v-model="showTimePicker" position="bottom">
      <van-datetime-picker
        v-model="dateValue"
        type="year-month"
        title="选择年和月"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="confirmDate"
        @cancel="showTimePicker = false"
      />
    </van-popup>
  </div>
</template>

<script>
import {Toast} from 'vant'
export default {
  name: 'comSearchByDate',
  props: {
    label: String
  },
  data() {
    return {
      calendarValue: '',
      showTimePicker: false,
      minDate: new Date(2022, 0, 1),
      maxDate: new Date(2032, 12, 1),
      // 默认为当前月份
      dateValue: new Date()
    }
  },
  methods: {
    toResetCalendarValue() {
      this.calendarValue = '';
    },
    confirmDate(time) {
      if (time) {
        this.calendarValue = this.$needDateFormat(time, 'yyyy-MM');
      } else {
        this.calendarValue = ''
      }
      this.showTimePicker = false
    },
    doSearchByDate() {
      if (this.calendarValue){
        this.$emit('getCalendarValue', this.calendarValue)
      } else {
        Toast('请先选择时间！')
      }
    }
  }
}
</script>

<style scoped></style>
